package com.boxuegu.myapplication.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.boxuegu.myapplication.bean.VideoBean;
import com.boxuegu.myapplication.sqlite.SQLiteHelper;


import java.util.ArrayList;
import java.util.List;

public class DBAccess {//用来访问数据表CRUD，里面必须使用SQLiteHelper
    private static DBAccess dbAccess=null;
    private SQLiteDatabase readDB;
    private SQLiteDatabase writeDB;

    private DBAccess(Context context) {
        SQLiteHelper helper=new SQLiteHelper(context);
        readDB=helper.getReadableDatabase();
        writeDB=helper.getReadableDatabase();
    }

    public static DBAccess getDBAccessObject(Context context){
        if(dbAccess==null){
            dbAccess=new DBAccess(context);
        }
        return dbAccess;
    }

    public void saveVideoPlayList(String userName, VideoBean bean){//保存播放记录
        if(isPlayList(userName,bean)){//如果该记录存在，则删除
            delPlayList(userName,bean);
        }
        //插入记录
        ContentValues cv=new ContentValues();
        cv.put("userName",userName);
        cv.put("id",bean.id);
        cv.put("videoId",bean.videoId);
        cv.put("title",bean.title);
        cv.put("videoTitle",bean.videoTitle);
        cv.put("videoPath",bean.videoPath);
        writeDB.insert("videoPlayList",null,cv);

    }

    public void delPlayList(String userName, VideoBean bean){
        writeDB.delete("videoPlayList","userName=? and videoId=?",new String[]{userName,bean.videoId+""});
    }

    public boolean isPlayList(String userName, VideoBean bean){
        boolean is=false;
        String sql="select * from videoPlayList where userName=? and videoId=?";
        Cursor cursor=readDB.rawQuery(sql,new String[]{userName,bean.videoId+""});
        if(cursor.moveToFirst()){
            is=true;
        }
        return is;
    }
    public List<VideoBean> getVideoPlayHistory(String userName){
        String sql="select * from videoPlayList where userName=?";
        Cursor cursor=readDB.rawQuery(sql,new String[]{userName});
        List<VideoBean> beans=new ArrayList<VideoBean>();
        while (cursor.moveToNext()){
            VideoBean bean=new VideoBean();
            bean.id=cursor.getInt(cursor.getColumnIndex("id"));
            bean.videoId=cursor.getInt(cursor.getColumnIndex("videoId"));
            bean.title=cursor.getString(cursor.getColumnIndex("title"));
            bean.videoTitle=cursor.getString(cursor.getColumnIndex("videoTitle"));
            bean.videoPath=cursor.getString(cursor.getColumnIndex("videoPath"));
            beans.add(bean);
        }
        return beans;
    }
}